package com.mgee.netty.server.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
	public static<T> T ObjectToDTO(Object obj, Class<T> A) throws IOException {
		if(obj == null) return null;
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(obj);
		T dtoObj = mapper.readValue(json, A);
		return dtoObj;

	}
	
	public static String ObjectToString(Object obj) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(obj);
		return json;

	}
	
	public static<T> T stringToObject(String str, Class<T> A) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		T obj = mapper.readValue(str, A);
		return obj;

	}
	
	@SuppressWarnings("unchecked")
	public static <T> Object stringToListObject(String str, Class<T> A) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		if(A == String.class) {
			List<String> obj = mapper.readValue(str, ArrayList.class);
			return obj;
		}else {
			JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, A);
			List<T> obj = mapper.readValue(str, jt);
			return obj;
		}
	}
	
	public static <T> List<T> listToListObject(List<?> objList, Class<T> A) throws IOException {
		List<T> results = new ArrayList<T>(objList.size());
		for(Object obj : objList) {
			results.add((T)ObjectToDTO(obj, A));
		}
		return results;
	}

}
